package com.live.dengdengtv.fragment.hall;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.HotTopicActivity;
import com.live.dengdengtv.activity.support.CurLiveInfo;
import com.live.dengdengtv.activity.live.LiveingActivity;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.LoginInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.LiveInfoItem;
import com.live.dengdengtv.bean.gson.TopicRecommend;
import com.live.dengdengtv.fragment.BaseFragment;
import com.live.dengdengtv.bean.Constants;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.utils.DpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by wyf on 2016/8/5.
 */
public class RecentFragment extends BaseFragment {

    private static RecentFragment fragment = new RecentFragment();
    public static RecentFragment getInstance(){
        return fragment;
    }

    private View contentView;
    private GridView hot_topic_gv;//热门话题

    private GridView recent_live_gv;//最新直播

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (contentView == null) {

            contentView = inflater.inflate(R.layout.activity_recent_live, container, false);
            //热门话题GridView
            getHotTopicData(contentView);
            //最新直播GridView
            getRecentLiveData(contentView);
        }
        return contentView;
    }

    private List<String> topicList = new ArrayList<String>();
    private BaseAdapter topicAdapter;
    public void getHotTopicData(View view){
        hot_topic_gv = (GridView)(view.findViewById(R.id.hot_topic_gv));
        topicAdapter = new GridAdapter(getActivity(), topicList);
        hot_topic_gv.setAdapter(topicAdapter);

        hot_topic_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 5) {
                    //打开热门话题页面
                    Intent intent = new Intent(getActivity(), HotTopicActivity.class);
                    startActivity(intent);
                } else {
                    //
                }
            }
        });
        getRecommend();//获取推荐话题
    }


    private ArrayList<LiveInfoItem> liveList = new ArrayList<LiveInfoItem>();
    private BaseAdapter recentLiveAdapter;
    public void getRecentLiveData(View view){
        recent_live_gv = (GridView)view.findViewById(R.id.recent_live_gv);
        recentLiveAdapter = new RecentLiveAdapter(getActivity());
        recent_live_gv.setAdapter(recentLiveAdapter);

        recent_live_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //如果是自己
                LiveInfoItem item = liveList.get(position);
                if (item.getCreator_id().equals(LoginInfo.getInstance().getUserId())) {
                    Intent intent = new Intent(getActivity(), LiveingActivity.class);
                    intent.putExtra(Constants.ID_STATUS, Constants.HOST);
                    CurLiveInfo.setIdStatus(Constants.HOST);
                    CurLiveInfo.setJoinRoomWay(false);
                    CurLiveInfo.setHostID(item.getCreator_id());
                    CurLiveInfo.setHostName(item.getCreator_nickname());
                    CurLiveInfo.setAvatorurl(item.getCover());
                    CurLiveInfo.setRoomNum(Integer.parseInt(item.getLive_room_id()));
                    CurLiveInfo.setMembers(Integer.parseInt(item.getCount_of_looker())); // 添加自己
                    CurLiveInfo.setAdmires(Integer.parseInt(item.getCount_of_admire()));
                    CurLiveInfo.setAddress("北京");
                    CurLiveInfo.setLiveId(item.getId());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), LiveingActivity.class);
                    intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
                    CurLiveInfo.setIdStatus(Constants.MEMBER);
                    CurLiveInfo.setJoinRoomWay(false);
                    CurLiveInfo.setHostID(item.getCreator_id());
                    CurLiveInfo.setHostName(item.getCreator_nickname());
                    CurLiveInfo.setAvatorurl(item.getCover());
                    CurLiveInfo.setRoomNum(Integer.parseInt(item.getLive_room_id()));
                    CurLiveInfo.setMembers(Integer.parseInt(item.getCount_of_looker()) + 1); // 添加自己
                    CurLiveInfo.setAdmires(Integer.parseInt(item.getCount_of_admire()));
                    CurLiveInfo.setAddress("北京");
                    CurLiveInfo.setLiveId(item.getId());
                    startActivity(intent);
                }
            }
        });

        getPageData();
    }

    private void getRecommend(){
        HashMap<String,String> params = new HashMap<>();
        params.put("limit","5");
        params.putAll(AppInfo.getHeadInfo());
        requestData(NetTaskList.search_recommend, params, 1);
    }
    private void getPageData(){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("page","1");
        params.put("page_count","20");
        params.putAll(AppInfo.getHeadInfo());
        requestNetData(NetTaskList.live_list, params, 2, false);
    }
    @Override
    public boolean onResponse(SimpleInfoData response, int id) {
        if(response.result == 0){
            if (id == 1) {
                topicList.clear();
                JsonArray array = response.data.getAsJsonArray();
                for (int i=0; i<array.size() ;i++){
                    TopicRecommend liveItem = new Gson().fromJson(array.get(i).getAsJsonObject(), TopicRecommend.class);
                    topicList.add("#"+liveItem.content+"#");
                }
                topicList.add("热门话题>");
                topicAdapter.notifyDataSetChanged();
            }else if(id == 2){
                JsonArray array = response.data.getAsJsonArray();
                for (int i=0; i<array.size() ;i++){
                    LiveInfoItem liveItem = new Gson().fromJson(array.get(i).getAsJsonObject(), LiveInfoItem.class);
                    liveList.add(liveItem);
                }
                recentLiveAdapter.notifyDataSetChanged();
            }
        }
        return false;
    }


    //热门话题的GridView
    public class GridAdapter extends BaseAdapter {

        private Context context;
        private List<String> texts;

        public GridAdapter(Context context, List<String> texts){
            this.context = context;
            this.texts = texts;
        }

        @Override
        public int getCount() {
            return texts.size();
        }

        @Override
        public Object getItem(int position) {
            return texts.size();
        }

        @Override
        public long getItemId(int position) {
            return texts.size();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv;
            if(convertView==null){
                tv = new TextView(context);
                tv.setGravity(Gravity.CENTER);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);//12sp
                tv.setTextColor(0XFF999999);//#999999
                tv.setBackgroundColor(0xFFfcf8f9);
                AbsListView.LayoutParams param = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DpUtil.dip2px(context,50));//40dp
                tv.setLayoutParams(param);

            }else{
                tv = (TextView)convertView;
            }
            tv.setText(texts.get(position));
            return tv;
        }
    }

    //最新直播的GridView
    public class RecentLiveAdapter extends BaseAdapter{
        private LayoutInflater mInflater;

        public RecentLiveAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return liveList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.gridview_recent_live_item, null);
                holder = new ViewHolder();
                /*得到各个控件的对象*/
                holder.person_iv = (ImageView) convertView.findViewById(R.id.person_iv);
                holder.star_level_iv = (ImageView) convertView.findViewById(R.id.star_level_iv);
                holder.province_tv=(TextView) convertView.findViewById(R.id.province_tv);

                convertView.setTag(holder); //绑定ViewHolder对象
            }
            else {
                holder = (ViewHolder) convertView.getTag(); //取出ViewHolder对象
            }
            LiveInfoItem data = liveList.get(position);

            if (!TextUtils.isEmpty(data.getCover())){
                RequestManager req = Glide.with(getContext());
                req.load(data.getCover()).into(holder.person_iv);
//                ImageLoader.getInstance().displayImage(data.getCover(),holder.person_iv);
            }else{
                holder.person_iv.setImageResource(R.mipmap.testpic);
            }
            return convertView;
        }
    }

    /*存放控件 的ViewHolder*/
    public final class ViewHolder {
        public ImageView person_iv;//头像
        public ImageView star_level_iv;//等级
        public TextView province_tv;//省份
    }

}
